import { ref, onMounted, onUnmounted, Ref } from 'vue'

const useClickOutside = (elementRef: Ref<null | HTMLElement>) => {
    const isClickOutside = ref(false)
    // e: MouseEvent 鼠标事件
    const handler = (e: MouseEvent) => {
        if(elementRef.value) {
            // contains 包含
            if(elementRef.value.contains(e.target as HTMLElement)) {
                isClickOutside.value = false
            } else { 
                isClickOutside.value = true
            }
        }
    }
    // 挂载完成后调用
    onMounted(() => {
        document.addEventListener('click', handler)
    })
    // 销毁前调用
    onUnmounted(() => {
        document.removeEventListener('click', handler)
    })
    return isClickOutside
}

export default useClickOutside